(async function () {
  const db = require('mysql2-promise')();
  const koa = require('koa');
  const Router = require('koa-router');
  const bodyparser = require('koa-bodyparser');
  const fs = require('fs');
  const static = require("koa-static");
  const path = require("path");
  const cors = require('koa-cors');
  const koaBody = require('koa-body');
  const app = new koa();
  const router = new Router();
  const jwt = require('jsonwebtoken');

  app.use(cors());
  // app.use(bodyparser());
  app.use(static(path.join(__dirname, "/static")));
  //配置前端页面静态资源
  // app.use(static('./static', {
  //   prefix: '/static',
  //   gzip: true,
  // }));
  app.use(koaBody({ multipart: true }));
  app.use(async (ctx, next) => { // 请求中间件
    console.log(`${ctx.request.method} ${ctx.request.url}`); // 打印URL
    await next(); // 调用下一个middleware
  });

  // 链接数据库
  db.configure({
    'host': 'localhost',
    'user': 'root',
    'password': '12345678',
    'database': 'toutiao'
  });
  // let arr = await db.query("SELECT * FROM users");
  // console.log(arr[0]);

  // router.get('/list', async ctx => {
  //   let [data] = await db.query("SELECT * FROM users");
  //   console.log(ctx.query)
  //   // let token = jwt.sign({
  //   //   username: req.query.username//加密的对象
  //   // }, "abc")//加密算法
  //   ctx.body = {
  //       code: 200,
  //       data
  //     }
  // })

  function random () {
    var storage = (function (length = 10) {
      const data =
        ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
          "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y",
          "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
          "s", "t", "u", "v", "w", "x", "y", "z"];
      let nums = "";
      for (let i = 0; i < length; i++) {
        const r = parseInt(Math.random() * 61, 10);
        nums += data[r];
      }
      return nums + '.jpg';
    })();
    // console.log(storage);
    return storage;
  }
  // 上传素材
  router.post('/user/images', async (ctx) => {
    try {
      // 前端传单个的话则为对象，若多个File的话则为File数组
      const files = ctx.request.files
    //   console.log(ctx.request.files)
    //   console.log(files.image);
      const img = fs.readFileSync(files.image.path);
      const storage = random();
      fs.writeFileSync('./static/uploads/' + storage, img);
    //   console.log(img);
    //   console.log(ctx.request.body);
      db.query(`insert into image (user_id, img) values(1,'${storage}')`);
      let [data] = await db.query(`SELECT * FROM image where user_id = 1 `);
      // let [data] = await db.query(`SELECT * FROM users where mobile = ${mobile} and code = ${code}`);
    //   console.log(data[0].img);
      // 额外的参数，需要使用ctx.request.body获取
      // const { data1, data2 } = ctx.request.body

      return ctx.body = { url: `/uploads/${storage}` }
    } catch (err) {
      console.log(err);
      return ctx.body = { 'err': err }
    }
  })
  //登录
  router.post('/login', async ctx => {
    // const Axios = require("axios");
    // const result = await Axios({
    //   url:api+'/login',
    //   data:ctx.request.body
    // });
    // ctx.body = result; 
    // console.log('进来了');
    const { mobile, code } = ctx.request.body;
    try {
      let [data] = await db.query(`SELECT * FROM users where mobile = ${mobile} and code = ${code}`);
      console.log(data);
      if (data.length === 0) {
        return ctx.body = {
          status: 401,
          messgae: "查无此人"
        }
      }
      let token = jwt.sign({
        mobile: ctx.request.body.mobile//加密的对象
      }, 'luo')//加密算法
      console.log(token)
      return ctx.body = {
        code: 200,
        token
      };
    } catch {
      return ctx.body = {
        status: 401,
        messgae: '格式不正确'
      }
    }
  })
  //验证token函数
  function verify (opt) {
    let key = opt.header.authorization;
    let token = key.slice(0, 7);
    if (token != 'Bearer ') return;
    let user = key.slice(7);
    // console.log(user);
    let mobile = jwt.verify(user, 'luo', (err, decode) => {
      // console.log("err", err);
      // console.log("decode", decode);
      return decode.mobile;
    })
    return mobile;
  }
  // 获取用户信息
  router.get('/user/profile', async ctx => {
    // console.log(ctx.request);
    var key = verify(ctx.request)
    let [data] = await db.query(`SELECT * FROM users where mobile = ${key}`);
    const {name,photo,intro,email,id,mobile} = data[0];
    // console.log(data[0]);
    ctx.body = {
      status: 200,
      name,
      photo,
      intro,
      email,
      id,
      mobile
    }
  })
// 上传用户头像
  router.post('/user/photo', async ctx => {
    // console.log(ctx.request);
    var key = verify(ctx.request)
    let [data] = await db.query(`SELECT * FROM users where mobile = ${key}`);
    // console.log(data[0]);
    // 前端传单个的话则为对象，若多个File的话则为File数组
    const files = ctx.request.files
    // console.log(ctx.request)
    // console.log(files.photo);
    // console.log(files);
    const img = fs.readFileSync(files.image.path);
    const storage = random();
    fs.writeFileSync('./static/uploads/' + storage, img);
    let a =await db.query(`update users SET photo = '${storage}' where id = ${data[0].id}`);
    // console.log(a);
    let [data1] = await db.query(`SELECT * FROM users where mobile = ${key} `);
    ctx.body = {
      status: 200,
      name: data1[0].name,
      photo: `${data1[0].photo}`
    }
  })
  // 修改用户信息
  router.post('/user/profile', async ctx => {
    // console.log(ctx.request.body);
    const { name:name1, intro:intro1, email:email1 } = ctx.request.body;
    let key = verify(ctx.request)
    db.query(`update users SET name = '${name1}',intro = '${intro1}',email = '${email1}' where mobile = ${key}`);
    // let [data] = await db.query(`SELECT * FROM users where mobile = ${key}`);
    // const {name:name2, intro:intro2, email:email2, photo:photo2} = data[0];
    ctx.body = {
      status: 200,
      message:'修改成功'
    }
  })


  // 获取用户的素材
  router.get('/user/images', async ctx => {
    // console.log(ctx.request);
    var key = verify(ctx.request)
    let [Data] = await db.query(`SELECT * FROM users where mobile = ${key}`);
    let [data] = await db.query(`SELECT * FROM image where user_id = ${Data[0].id}`);
    // console.log(data);
    ctx.body = {
      status: 200,
      data
    }
  })

  // 发布文章
  router.post('/articles', async ctx => {
    // console.log(ctx.request.query);
    const {title,content,type,channel_id,img} = ctx.request.body
    // console.log(ctx.request.body);
    var key = verify(ctx.request)
    let status = '2'
    // console.log(typeof(ctx.request.query.draft))
    if(ctx.request.query.draft === 'true'){
        status = '0'
    }
    let [Data] = await db.query(`SELECT * FROM users where mobile = ${key}`);
    let a = await db.query(`insert into article (title, content,type,channel_id,user_id,img,status) values('${title}','${content}','${type}',${channel_id},${Data[0].id},'${img}',${status})`);
// console.log(ctx.request.query.draft+'999999999999999999')
    // db.query(`insert into image (user_id, article_id,img) values(${Data[0].id},'${data2}')`);
    console.log(status);
    ctx.body = {
      status: 200,
      // data
    }
  })

  // 获取文章列表
  router.get('/articles', async ctx => {
    // console.log(ctx.request.query);
    const {page,per_page, status, channel_id} = ctx.request.query;
    var key = verify(ctx.request)
    let [Data] = await db.query(`SELECT * FROM users where mobile = ${key}`);
    // 获取所需的条数
    let [data] = await db.query(`SELECT * FROM article where user_id = ${Data[0].id} ${channel_id?('and channel_id = '+channel_id):''} ${status?('and status = '+status):''} limit ${(page-1)*per_page},${page*per_page}`);
    // console.log(data);
    // 获取总共多少条
    let [data1] = await db.query(`SELECT * FROM article where user_id = ${Data[0].id} ${channel_id?('and channel_id = '+channel_id):''} ${status?('and status = '+status):''}`);
    // console.log(data);
    ctx.body = {
      status: 200,
      data,
      totalCount:data1.length
    }
  })

// 修改文章先获取id
  router.get(`/articles/appoint`, async ctx => {
    console.log(ctx.request.query);
    let [data] = await db.query(`SELECT * FROM article where id = ${ctx.request.query[0]}`);
    ctx.body = {
      status: 200,
      data:data[0],
    }
  })
// 修改文章
  router.put('/articles', async ctx => {
    const {draft, target} = ctx.request.query
    const {title,content,type,channel_id,img} = ctx.request.body
    // console.log(ctx.request.body);
    // var key = verify(ctx.request)
    // let [Data] = await db.query(`SELECT * FROM users where mobile = ${key}`);
    let a = await db.query(`update article SET title = '${title}',content = '${content}',type = '${type}',img = '${img}',channel_id = ${channel_id} where id = ${target}`);
    // db.query(`insert into image (user_id, article_id,img) values(${Data[0].id},'${data2}')`);
    // console.log(a);
    ctx.body = {
      status: 200,
      // data
    }
  })
  
// 删除文章
router.delete('/articles', async ctx => {
  const {target} = ctx.request.query;
  let a = await db.query(`delete from article where id = ${target}`);
  console.log(a);
  ctx.body = {
    status: 200,
    // data
  }
})
// 获取频道列表
router.get('/channels', async ctx => {
  // var key = verify(ctx.request)
  let [data] = await db.query(`SELECT * FROM channel `);
  // let [data] = await db.query(`SELECT * FROM image where user_id = ${Data[0].id}`);
//   console.log(data);
  ctx.body = {
    status: 200,
    data
  }
})






  //jsonp方式获取数据
  router.get('/test', async ctx => {
    // let [data] = await db.query("SELECT * FROM users");
    let data = { a: 899 };
    console.log(JSON.stringify(data));
    back('{"a":899}')
    console.log('beiqqiukl');
    console.log(ctx.request.query);
    var str = ctx.request.query.callback + '(' + JSON.stringify(data) + ')';//jsonp   back("{}")
    ctx.body = str;
  })
  //测试接口
  router.get('/test1', async ctx => {
    // let [data] = await db.query("SELECT * FROM users");
    let data = { a: 899 }
    data = JSON.stringify(data)
    ctx.body = {
      data
    };
  })

  app.use(router.routes());
  app.listen(8081);
  console.log('链接成功');

})();